package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.WorkspaceService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
// 1.创建order对象，查看购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.findByCondition(shoppingCart);
//        list为空那么就意味着无数据
        if (list == null && list.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        }
//        否则生成订单
        Orders orders = new Orders();
//        1.1 补充数据
//           1.1.1 copy数据
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
//           1.1.2 补充
        orders.setNumber(UUID.randomUUID().toString().replace("-", ""));
        orders.setStatus(1);//订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(1);
        orders.setPayStatus(0);//支付状态 0未支付 1已支付 2退款
//        用户地址信息,根据提供的地址Id查询地址簿
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        orders.setPhone(address.getPhone());
        orders.setAddress(address.getProvinceName() + address.getCityName() + address.getDistrictName() + address.getDetail());
//       用户信息
        User user = userMapper.findById(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        orders.setConsignee(address.getConsignee());
//        将orders插入进表，并主键返回
        orderMapper.insert(orders);

//新建一个orderdetail对象
//        2.将购物车数据装进细节表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
//            将明细表数据插入进明细表中
            orderDetailMapper.add(orderDetail);
        }
//        3封装返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime()).build();

        if (orderSubmitVO != null) {
            log.info("生成订单成功，id为：{}", orderSubmitVO.getId());
//           4、清空购物车
            shoppingCartMapper.delete(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
            log.info("清空{}的购物车成功", BaseContext.getCurrentId());
            return orderSubmitVO;
        }
        log.info("订单生成失败！");
        return null;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.findById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = WeChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        log.info("支付成功，开始修改订单状态，并且推送接单消息");
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);
        log.info("订单号：{}", outTradeNo);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

    }

    /**
     * 模拟支付成功，修改状态
     *
     * @param ordersPaymentDTO
     */
    @Override
    public void updateStatus(OrdersPaymentDTO ordersPaymentDTO) {
        Orders order = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), BaseContext.getCurrentId());
        order.setPayStatus(1);
        order.setStatus(2);
        order.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(order);
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", order.getId());
        map.put("content", "订单号：" + order.getNumber());


        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        log.info("开始推送消息：" + map.toString());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 拒绝订单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        //购物车里有菜品
        shoppingCartMapper.delete(ShoppingCart.builder().userId(id).build());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 接单
     *
     * @param
     */
    @Override
    public void takeOrder(OrdersConfirmDTO ordersConfirmDTO) {
//将状态更换为待派送（派送中）
        orderMapper.update(Orders.builder().id(ordersConfirmDTO.getId()).status(4).build());

    }

    /**
     * 查看订单
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO inquire(Long id) {
        Orders orders = orderMapper.getById(id);

// 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

// 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;

    }

    /**
     * 根据id查询用户订单
     *
     * @param ordersConfirmDTO
     * @return
     */
    @Override
    public Orders getById(OrdersConfirmDTO ordersConfirmDTO) {
        return orderMapper.getById(ordersConfirmDTO.getId());

    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        Page<Orders> page = (Page<Orders>) orderMapper.select(dto);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return pageResult;
    }

    /**
     * 统计数量
     *
     * @param
     * @return
     */
    @Override
    public OrderStatisticsVO count() {
        OrderStatisticsVO vo = new OrderStatisticsVO();
        vo.setConfirmed(orderMapper.count(3));
        vo.setDeliveryInProgress(orderMapper.count(4));
        vo.setToBeConfirmed(orderMapper.count(2));
        return vo;

    }

    /**
     * 拒绝订单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {

        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());

        if (orders != null && orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            orders.setStatus(Orders.CANCELLED);
            int payStatus = orders.getPayStatus();
            if (payStatus == Orders.PAID) {
                orders.setPayStatus(2);
            }
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());

        }


        orderMapper.update(orders);


    }

    /**
     * 取消订单
     *
     * @param cancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO cancelDTO) {
        Orders orders = orderMapper.getById(cancelDTO.getId());

        if (orders != null) {
            orders.setStatus(Orders.CANCELLED);
            int payStatus = orders.getPayStatus();
            if (payStatus == Orders.PAID) {
                orders.setPayStatus(2);
            }
            orders.setCancelReason(cancelDTO.getCancelReason());
            orders.setCancelTime(LocalDateTime.now());
        }

        orderMapper.update(orders);
    }

    /**
     * 用户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
//        要得到时间列表字符串，金额总数字符串
//        1.得到时间列表
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
//        2.得到营业额集合
//        2.1. 得到每一天
        List<Double> turnoverList = new ArrayList<>();
//        Integer status = 5;
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

//        2.2. 得到每一天的营业额

            Map<String, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
//            Double amount = orderMapper.getAmount(status, beginTime, endTime);
            Double amount = orderMapper.getAmount(map);
//            2.3. 收集为金额集合
            turnoverList.add(amount == null ? 0.0 : amount);
        }
//        2.3.转为字符串
        String dateStr = dateList.stream().map(LocalDate::toString).collect(Collectors.joining(","));
        String turnStr = turnoverList.stream().map(Object::toString).collect(Collectors.joining(","));


        return TurnoverReportVO.builder()
                .dateList(dateStr)
                .turnoverList(turnStr)
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO countUser(LocalDate begin, LocalDate end) {
//需要得到日期列表字符串，用户总量，新增用户
//        1先得到时间日期集合
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
//2得到新增用户
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> usersList = new ArrayList<>();
//2.1 得到每一天
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
//制作参数传给mapper层
            Map<String, Object> map = new HashMap<>();

            map.put("endTime", endTime);
//            map.put("status", Orders.COMPLETED);
//            总用户量也就是今天之前包括今天的都算
            Integer totalUser = orderMapper.getUser(map);

            map.put("beginTime", beginTime);
//            当天新增用户则需要限制时间
            Integer number = orderMapper.getUser(map);
            usersList.add(totalUser);
            newUserList.add(number);
        }
//        转换为字符串
        String dateStr = dateList.stream().map(LocalDate::toString).collect(Collectors.joining(","));
        String newUserStr = newUserList.stream().map(Object::toString).collect(Collectors.joining(","));
        String usersStr = usersList.stream().map(Object::toString).collect(Collectors.joining(","));
//封装返回
        return UserReportVO.builder().dateList(dateStr)
                .newUserList(newUserStr)
                .totalUserList(usersStr)
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO countOrder(LocalDate begin, LocalDate end) {
//        需要查出日期列表，订单总数，有效订单数
//        日期
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
//        查表
        List<Integer> totalOrders = new ArrayList<>();
        List<Integer> validOrder = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Integer numberTotal = orderMapper.getUser(map);
            map.put("status", Orders.COMPLETED);
            Integer validNumber = orderMapper.getUser(map);
            totalOrders.add(numberTotal);
            validOrder.add(validNumber);
        });

//        需要给出有效订单数，订单总数，计算出订单完成率，
//有效订单数，reduce可以在流中递加
        Integer validNumbers = validOrder.stream().reduce(Integer::sum).get();
//总订单数
        Integer totalNumbers = totalOrders.stream().reduce(Integer::sum).get();
//完成率
        Double complatePoint = validNumbers * 1.0 / totalNumbers;

//        解析为字符串
//        日期字符串
        String dateStr = dateList.stream().map(LocalDate::toString).collect(Collectors.joining(","));
//总订单数字符串
        String totalStr = totalOrders.stream().map(Object::toString).collect(Collectors.joining(","));
//   有效订单字符串
        String validStr = validOrder.stream().map(Object::toString).collect(Collectors.joining(","));

//封装返回
        return OrderReportVO.builder()
                .dateList(dateStr)
                .validOrderCountList(validStr)
                .orderCountList(totalStr)
                .orderCompletionRate(complatePoint)
                .totalOrderCount(totalNumbers)
                .validOrderCount(validNumbers)
                .build();
    }

    /**
     * 查询销量排名前十的菜品
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

//        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
//        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));
        map.put("status", Orders.COMPLETED);

        List<GoodsSalesDTO> goodList = orderMapper.getTop(map);

        String nameList = goodList.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(","));
        String numberList = goodList.stream().map(GoodsSalesDTO -> GoodsSalesDTO.getNumber().toString()).collect(Collectors.joining(","));
        return SalesTop10ReportVO.builder().nameList(nameList).numberList(numberList).build();
    }

    /**
     * 导出经营数据
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) throws IOException {
//      1.  基于模板创建工作簿
        XSSFWorkbook wb = new XSSFWorkbook(this.getClass().getClassLoader().getResourceAsStream("template.xlsx"));

//       2. 创建表
        XSSFSheet sheet = wb.getSheetAt(0);
//2.1  时间
        LocalDate end = LocalDate.now();
        LocalDate begin = end.minusDays(29);
//        3.得到单元格赋值
        sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
        BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        sheet.getRow(3).getCell(2).setCellValue(data.getTurnover());
        sheet.getRow(3).getCell(4).setCellValue(data.getOrderCompletionRate());
        sheet.getRow(3).getCell(6).setCellValue(data.getNewUsers());
        sheet.getRow(4).getCell(2).setCellValue(data.getValidOrderCount());
        sheet.getRow(4).getCell(4).setCellValue(data.getUnitPrice());
//        4.明细表赋值
        int startRow = 7;
        while (!begin.isAfter(end)) {
            BusinessDataVO data1 = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(begin, LocalTime.MAX));

            sheet.getRow(startRow).getCell(1).setCellValue(begin.toString());
            sheet.getRow(startRow).getCell(2).setCellValue(data1.getTurnover());
            sheet.getRow(startRow).getCell(3).setCellValue(data1.getValidOrderCount());
            sheet.getRow(startRow).getCell(4).setCellValue(data1.getOrderCompletionRate());
            sheet.getRow(startRow).getCell(5).setCellValue(data1.getUnitPrice());
            sheet.getRow(startRow).getCell(6).setCellValue(data1.getNewUsers());

            startRow++;


            begin = begin.plusDays(1);
        }

    }
}

